package com.jucai.pppeiyouclient.view.fragment;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.adapter.MerchantServiceAdapter;
import com.jucai.pppeiyouclient.base.BaseFragment;
import com.jucai.pppeiyouclient.base.CommonRecyclerViewAdapter;
import com.jucai.pppeiyouclient.bean.MerchantServiceBean;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.view.activity.BrowserActivity;
import com.jucai.pppeiyouclient.view.activity.CommonH5Activity;
import com.jucai.pppeiyouclient.view.activity.SettingActivity;
import com.jucai.pppeiyouclient.weidget.pulltorefresh.PullToRefreshForRecyclerView;
import com.jucai.pppeiyouclient.weidget.pulltorefresh.PullToRefreshLayout;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Kuky on 2017-05-06.
 */

public class MerchantApplyFragment extends BaseFragment implements PullToRefreshLayout.OnRefreshListener {
    private static final String TAG = "MerchantApplyFragment : ";
    private PullToRefreshLayout refreshLayout;
    private PullToRefreshForRecyclerView serviceRv;
    private List<MerchantServiceBean> services = new ArrayList<>();
    private MerchantServiceAdapter serviceAdapter;
    private Handler mHandler = new Handler();
    private int page = 1;

    @Override
    protected void initView() {
        serviceAdapter = new MerchantServiceAdapter(getActivity(), services);
        refreshLayout = (PullToRefreshLayout) itemView.findViewById(R.id.refresh_view);
        serviceRv = (PullToRefreshForRecyclerView) itemView.findViewById(R.id.content_view);
        serviceRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        serviceRv.setItemAnimator(new DefaultItemAnimator());
        serviceRv.setAdapter(serviceAdapter);
        serviceAdapter.setOnItemClickListener(new CommonRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                MerchantServiceBean o = services.get(position);
                if (!TextUtils.isEmpty(o.getURL())) {
                    SharedPreferencesUtil.saveStringPreference(getActivity(), "HISTORY", "his_url", o.getURL());
                    Intent intent = new Intent(getActivity(), CommonH5Activity.class);
                    intent.putExtra("url", o.getURL());
                    startActivity(intent);
                    LogUtils.e(TAG + "url = " + o.getURL());
                }
            }

            @Override
            public void onItemLongClickListener(View view, int position) {

            }
        });
    }

    @Override
    protected void initData() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Find_Order.getOrderList");
        param.put("member_id", LoginUtils.getMember_id(getContext()));
        param.put("token", LoginUtils.getToken(getContext()));
        param.put("status", "new");
        page = 1;//进入页面先获取第一页的数据
        param.put("page",page+"");

        CommonRequestNetData.getJsonArrayData(getActivity(), param,true, new CommonRequestNetData.JsonArrayCallBack() {
            @Override
            public void parseJsonArray(JSONArray jsonArray) {
                LogUtils.e(TAG + "jsonArray = " + jsonArray.toString());
                services = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<MerchantServiceBean>>() {
                }.getType());
                if(!services.isEmpty()){
                    page++;
                }
                LogUtils.e("services = " + services.toString());
                serviceAdapter.setData(services);
            }
        });
    }

    @Override
    protected void loadNetData() {
        /**
         * 在onresume（）处调用，由于返回到此activity会再次调用，会造成数据再次从第一页获取数据，不符合逻辑，所以此处不做数据获取操作
         */
        /*HashMap<String, String> param = new HashMap<>();
        param.put("service", "Find_Order.getOrderList");
        param.put("member_id", LoginUtils.getMember_id(getContext()));
        param.put("token", LoginUtils.getToken(getContext()));
        param.put("status", "new");
        param.put("page",1+"");//进入

        CommonRequestNetData.getJsonArrayData(getActivity(), param,true, new CommonRequestNetData.JsonArrayCallBack() {
            @Override
            public void parseJsonArray(JSONArray jsonArray) {
                LogUtils.e(TAG + "jsonArray = " + jsonArray.toString());
                services = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<MerchantServiceBean>>() {
                }.getType());
                LogUtils.e("services = " + services.toString());
                serviceAdapter.setData(services);
            }
        });*/
    }

    private void loadMore(){
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Find_Order.getOrderList");
        param.put("member_id", LoginUtils.getMember_id(getContext()));
        param.put("token", LoginUtils.getToken(getContext()));
        param.put("status", "new");
        param.put("page",page+"");

        CommonRequestNetData.getJsonArrayData(getActivity(), param,true, new CommonRequestNetData.JsonArrayCallBack() {
            @Override
            public void parseJsonArray(JSONArray jsonArray) {
                LogUtils.e(TAG + "jsonArray = " + jsonArray.toString());
                List<MerchantServiceBean> servicePage = new ArrayList<>();
                servicePage = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<MerchantServiceBean>>() {
                }.getType());
                LogUtils.e("servicePage = " + servicePage.toString());
                if(!servicePage.isEmpty()){
                    page++;
                    services.addAll(servicePage);
                    serviceAdapter.setData(services);
                }
            }
        });
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnRefreshListener(this);
    }

    @Override
    protected int getFragmentViewId() {
        return R.layout.common_fragment_with_ptr;
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
               // initData();
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
        }, 500);
    }

    @Override
    public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //initData();
                loadMore();
                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }
        }, 500);
    }
}
